import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam_question.dart';
import 'package:kxy_flutter_app/view/examination/do_review_view.dart';

class CollectQuesView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CollectQuesViewState();
  }
}

class CollectQuesViewState extends State<CollectQuesView> {
  int page = 1;
  int totalCount = 0;
  Future loadFuture;
  List<Question> quesList = new List<Question>();

  @override
  void initState() {
    super.initState();
    loadFuture = reload();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return DoReviewView(
              title: '试题收藏',
              quesList: quesList,
              readonly: false,
              totalCount: totalCount,
              loadMore: loadMore,
              withCollect: true,
            );
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Future reload() async {
    page = 1;
    totalCount = 0;
    quesList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post(
      '/exam-app/coll/collQuesList',
      params: {
        'limit': 50,
        'page': page,
        'userId': Auth.instance.userId,
      },
    );

    if (res.code == 200) {
      setState(() {
        totalCount = res.data['totalCount'];
        (res.data['list'] as List).forEach((item) {
          var ques = Question.fromJson(item);
          ques.isCollect = true;
          if (quesList.indexWhere((x) => x.quesId == ques.quesId) == -1) {
            quesList.add(ques);
          }
        });
        page++;
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
